package com.qigao.erp.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qigao.erp.commons.UserService;
import com.qigao.erp.commons.dto.UserCondDto;
import com.qigao.erp.commons.dto.UserCreateDto;
import com.qigao.erp.commons.dto.UserResultDto;
import com.qigao.erp.commons.dto.UserUpdateDto;
import com.qigao.erp.commons.enums.*;
import com.qigao.erp.commons.utils.DateUtil;
import com.qigao.erp.commons.utils.IDUtils;
import com.qigao.erp.commons.utils.ThreeDESUtil;
import com.qigao.erp.jdbc.mapper.SysUserMapper;
import com.qigao.erp.jdbc.model.SysUser;
import org.apache.shiro.dao.DataAccessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public Page<UserResultDto> findUserPage(UserCondDto userCondDto) {
        //使用PageHelper类进行分页
        PageHelper.startPage(userCondDto.getPageNum(), userCondDto.getPageSize());
        Page<SysUser> sysUserPage = (Page) findList(userCondDto);
        Page<UserResultDto> topicResultDtoPage = convertDto(sysUserPage);
        return topicResultDtoPage;
    }

    @Override
    public Result<UserResultDto> findByUniqIndex(String uniqIndexNo) {
        SysUser sysUser = sysUserMapper.selectByIndex(uniqIndexNo);
        if (sysUser == null) {
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }
        UserResultDto userResultDto = buildSingleDto(sysUser);
        return Result.newSuccess(userResultDto);
    }

    @Override
    public Result createUser(UserCreateDto userCreateDto) {
        SysUser sysUser = sysUserMapper.selectByUserNo(userCreateDto.getUserNo());
        if (sysUser != null ) {
            return Result.newError(ResultCode.COMMON_DATA_EXISTS);
        }
        try{
            SysUser sysUser3 = new SysUser();
            BeanUtils.copyProperties(userCreateDto, sysUser3);
            if(StringUtils.isEmpty(userCreateDto.getUserNo())){
                sysUser3.setUserNo(IDUtils.genIdStr(IdTypeEnum.USER));
            }
            if(!StringUtils.isEmpty(userCreateDto.getLoginPass())){
                String signPass1 = ThreeDESUtil.encryptToHex(userCreateDto.getLoginPass());
                sysUser3.setLoginPass(signPass1);
            }
            sysUser3.setCreateNo(userCreateDto.getOperNo());
            sysUser3.setCreateTime(new Date());
            sysUser3.setModiNo(userCreateDto.getOperNo());
            sysUser3.setModiTime(new Date());
            sysUserMapper.insertSelective(sysUser3);
        }catch (DataAccessException e){
            logger.error("创建用户：{}信息已存在",userCreateDto);
            return Result.newError(ResultCode.COMMON_DATA_EXISTS);
        }
        return Result.newSuccess();
    }

    @Override
    public Result updateUser(UserUpdateDto userUpdateDto) {
        SysUser sysUser1 = sysUserMapper.selectByIndex(userUpdateDto.getUserNo());
        if(sysUser1==null){
            return Result.newError(ResultCode.COMMON_DATA_EXISTS);
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userUpdateDto, sysUser);
        sysUser.setModiNo(userUpdateDto.getOperNo());
        sysUser.setModiTime(new Date());
        sysUser.setVersion(sysUser1.getVersion());
        sysUserMapper.updateByUserNo(sysUser);
        return Result.newSuccess();
    }

    @Override
    public Result<String> deleteById(Integer id) {
        sysUserMapper.deleteByPrimaryKey(id);
        return Result.newSuccess();
    }

    @Override
    public List<UserResultDto> findAll() {
        List<SysUser> sysUsers = sysUserMapper.selectAll();
        List<UserResultDto> userResultDtos = new ArrayList<>();
        if (sysUsers != null && sysUsers.size() >= 1) {
            for (SysUser sysUser : sysUsers) {
                UserResultDto userResultDto = buildSingleDto(sysUser);
                userResultDtos.add(userResultDto);
            }
        }
        return userResultDtos;
    }

    @Override
    public Result update(UserUpdateDto userUpdateDto) {
        SysUser sysUser = new SysUser();
        sysUser.setId(Integer.valueOf(userUpdateDto.getId()));
        BeanUtils.copyProperties(userUpdateDto, sysUser);
       // sysUser.setIfAdmin(Integer.valueOf(userUpdateDto.getIfAdmin()==null?IfAdminEnum.NO.getCode():IfAdminEnum.YES.getCode()));
        if(!StringUtils.isEmpty(userUpdateDto.getLoginPass())){
            String signPass1 = ThreeDESUtil.encryptToHex(userUpdateDto.getLoginPass());
            sysUser.setLoginPass(signPass1);
        }
        sysUser.setModiNo(userUpdateDto.getOperNo());
        sysUser.setModiTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        return Result.newSuccess();
    }


    private Page<UserResultDto> convertDto(Page<SysUser> sysUserPage) {
        List<SysUser> sysUsers = sysUserPage.getResult();
        Page<UserResultDto> userResultDtoPage = new Page<UserResultDto>();
        BeanUtils.copyProperties(sysUserPage, userResultDtoPage);
        if (sysUsers != null && sysUsers.size() >= 1) {
            for (SysUser sysUser : sysUsers) {
                UserResultDto userResultDto = buildSingleDto(sysUser);
                userResultDtoPage.add(userResultDto);
            }
        }
        return userResultDtoPage;
    }

    private UserResultDto buildSingleDto(SysUser sysUser) {
        UserResultDto userResultDto = new UserResultDto();
        BeanUtils.copyProperties(sysUser, userResultDto);
        userResultDto.setStatusName(StatusEnum.getNameByCode(sysUser.getStatus()));
        userResultDto.setIfAdminName(IfAdminEnum.getNameByCode(sysUser.getIfAdmin()));
        userResultDto.setUserLevelName(UserLevelEnum.getNameByCode(sysUser.getUserLevel()));
        userResultDto.setUserTypeName(UserTypeEnum.getNameByCode(sysUser.getUserType()));
        userResultDto.setIfFormalName(IfFormulaEnum.getNameByCode(sysUser.getIfFormal()));
        userResultDto.setFormalDate(DateUtil.getDateFormat(sysUser.getFormalDate()));
        userResultDto.setEntryDate(DateUtil.getDateFormat(sysUser.getEntryDate()));
        userResultDto.setCreateTime(DateUtil.getDateTimeFormat(sysUser.getCreateTime()));
        userResultDto.setModiTime(DateUtil.getDateTimeFormat(sysUser.getModiTime()));
        SysUser inviteUser = sysUserMapper.selectByUserNo(userResultDto.getInviteUserNo());
        if(inviteUser!=null)
        userResultDto.setInviteUserName(inviteUser.getUserName());
       // String passWord = ThreeDESUtil.decryptHex(sysUser.getLoginPass());
       // userResultDto.setLoginPass(passWord);
        return userResultDto;
    }

    private List<SysUser> findList(UserCondDto userCondDto) {
        return sysUserMapper.selectList(userCondDto);
    }
}
